import { Injectable } from '@nestjs/common';
import { FindManyOptions, Repository } from 'typeorm';
import { PaginationQueryDto } from '../dto/pagination-query.dto';
import { PaginationResult } from '../interfaces/pagination-results.interface';
import { format } from 'date-fns';
import { TimestampedEntity } from '../interfaces/timestamped-entity.interface';

@Injectable()
export class PaginationService {
  async paginate<T extends TimestampedEntity>(
    repository: Repository<T>,
    paginationQuery: PaginationQueryDto & { where?: any },
    options?: FindManyOptions<T>,
  ): Promise<PaginationResult<T>> {
    const { page = 1, limit = 10, where, sortField, sortOrder } = paginationQuery;

    const offset = (page - 1) * limit;

    const queryOptions: FindManyOptions<T> = {
      skip: offset,
      take: limit,
      ...options,
      where,
    };

    if (sortField && sortOrder) {
      queryOptions.order = { [sortField]: sortOrder } as any; // 使用 `as any` 进行类型断言
    }

    const [data, total] = await repository.findAndCount(queryOptions);

    const formattedData = data.map(item => ({
      ...item,
      createdAt: item.createdAt ? format(new Date(item.createdAt), 'yyyy-MM-dd HH:mm:ss') : null,
      updatedAt: item.updatedAt ? format(new Date(item.updatedAt), 'yyyy-MM-dd HH:mm:ss') : null,
    }));

    return {
      items: formattedData,
      total,
      limit,
      page,
      offset,
    };
  }
}
